package com.wnxy.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectResult;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

@Component
@Data
@ConfigurationProperties(prefix = "aliyunoos")
public class AliyunTemplete {
    // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
    private String endpoint;
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    private String accessKeyId;
    private String accessKeySecret;

    public String upload(String bucketName, String filename, InputStream is) {
        OSS ossClient = null;
        try {
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            ossClient.putObject(bucketName, filename, is);
        }finally {
            if(ossClient!=null) ossClient.shutdown();
        }
        String url="https://"+bucketName+"."+endpoint+"/"+filename;
        return url;
    }
    public void delete(String bucketName, String filename){
        filename=filename.substring(filename.lastIndexOf("com")+4);
        System.out.println(filename);
        OSS ossClient = null;
        try {
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            ossClient.deleteObject(bucketName, filename);
        }finally {
            if(ossClient!=null) ossClient.shutdown();
        }
    }

}
